package utils;

import lombok.Data;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Data
public class ContextUtils {

    private static ClassPathXmlApplicationContext redisContext;

    static {
        redisContext = new ClassPathXmlApplicationContext("spring/spring-redis.xml");
    }

    public static void close(){
        redisContext.close();
    }

    public static ClassPathXmlApplicationContext getContext() {
        return redisContext;
    }

    public static void setContext(ClassPathXmlApplicationContext context) {
        ContextUtils.redisContext = context;
    }

    public static <T> T getBean(String name){
        return (T) redisContext.getBean(name);
    }

    private static SessionCallback callback = (SessionCallback) (RedisOperations redisOperations) -> {
        // 开启事务
        redisOperations.multi();
        // 将要执行的命令放入到队列中
        redisOperations.opsForValue().set("key2", "value2");
        Map<String,String> map = new HashMap();
        map.put("李姣", "加油，你会成为变得更加优秀有钱多金");
        map.put("李姣啊", "加油，你会实现你的梦想");
        map.put("李姣啊啊", "加油，有一天你会站在硅谷最高的黑客比赛中");
        redisOperations.opsForHash().putAll("belive", map);
        redisOperations.exec();
        Map belive = redisOperations.opsForHash().entries("belive");
        String str = "" + belive.get("李姣") + belive.get("李姣啊") + belive.get("李姣啊啊");
        System.out.println(str);
        return str;
    };

    public static SessionCallback getCallback() {
        return callback;
    }

    public static void setCallback(SessionCallback callback) {
        ContextUtils.callback = callback;
    }

    /**
     * 将文件转为字节数组
     */
    public static byte[] getFileToByte(File file) {
        if (!file.isFile() || !file.exists() || file.length() <= 0){
            return null;
        }
        byte[] bytes = new byte[(int) file.length()];
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byte[] by = new byte[2048];
            int ch;
            while ((ch = is.read(by)) != -1) {
                byteStream.write(by, 0, ch);
            }
            bytes =  byteStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

}
